package org.example.movie;

/**
 * @author zehua
 * @date 2023/11/7 9:38
 * @Description TODO
 * @since V1.1.0
 */

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.bytedeco.opencv.opencv_core.Mat;
import org.example.RtspInfo;

import static org.bytedeco.opencv.global.opencv_imgcodecs.imwrite;

/**
 * rtsp 视频帧 转为图片
 */

public class RtspStreamHandler {
    public static void main(String[] args) {
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(RtspInfo.RTSP_URL);
        OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat();
        try {
            grabber.start();
            Frame frame;
            int i = 0;
            while ((frame = grabber.grab()) != null) {
                // 将Frame转换为OpenCV Mat
                Mat mat = converter.convert(frame);
                if (mat != null && i % 30 == 0) {
                    // 保存帧到磁盘
                    imwrite("frame_" + i + ".jpg", mat);
                }
                i++;
            }
        } catch (FrameGrabber.Exception e) {
            e.printStackTrace();
        } finally {
            try {
                grabber.stop();
            } catch (FrameGrabber.Exception e) {
                e.printStackTrace();
            }
        }


    }

    private static void doSomethingWithTheFrame(Frame frame, int frameNumber) {
        // 这里添加分析帧的代码
        // ...
    }
}
